package cn.edu.tju.elm.service;

import cn.edu.tju.elm.model.OrderDetailet;
import cn.edu.tju.elm.model.Order;
import cn.edu.tju.elm.model.Food;
import cn.edu.tju.elm.repository.OrderDetailetRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
public class OrderDetailetService {

    private final OrderDetailetRepository orderDetailetRepository;

    // 构造器注入
    public OrderDetailetService(OrderDetailetRepository orderDetailetRepository) {
        this.orderDetailetRepository = orderDetailetRepository;
    }

    /**
     * 添加订单项
     */
    @Transactional
    public OrderDetailet addOrderDetailet(OrderDetailet detailet) {
        return orderDetailetRepository.save(detailet);
    }

    /**
     * 批量添加订单项
     */
    @Transactional
    public List<OrderDetailet> batchAddOrderDetailets(List<OrderDetailet> detailets) {
        return orderDetailetRepository.saveAll(detailets);
    }

    /**
     * 根据ID查询订单项
     */
    @Transactional(readOnly = true)
    public Optional<OrderDetailet> getOrderDetailetById(Long id) {
        return orderDetailetRepository.findById(id);
    }

    /**
     * 查询订单下的所有订单项
     */
    @Transactional(readOnly = true)
    public List<OrderDetailet> getDetailetsByOrder(Order order) {
        return orderDetailetRepository.findByOrder(order);
    }

    /**
     * 查询食品在哪些订单项中出现
     */
    @Transactional(readOnly = true)
    public List<OrderDetailet> getDetailetsByFood(Food food) {
        return orderDetailetRepository.findByFood(food);
    }

    /**
     * 更新订单项数量
     */
    @Transactional
    public Optional<OrderDetailet> updateQuantity(Long id, Integer quantity) {
        Optional<OrderDetailet> detailetOpt = orderDetailetRepository.findById(id);
        if (detailetOpt.isPresent()) {
            OrderDetailet detailet = detailetOpt.get();
            detailet.setQuantity(quantity);
            return Optional.of(orderDetailetRepository.save(detailet));
        }
        return Optional.empty();
    }

    /**
     * 删除订单项
     */
    @Transactional
    public boolean deleteOrderDetailet(Long id) {
        if (orderDetailetRepository.existsById(id)) {
            orderDetailetRepository.deleteById(id);
            return true;
        }
        return false;
    }

    /**
     * 删除订单下的所有订单项
     */
    @Transactional
    public void deleteDetailetsByOrder(Order order) {
        orderDetailetRepository.deleteByOrder(order);
    }
}